#include "parkingspotpage.h"
#include "ui_parkingspotpage.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QLabel>
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QString>
#include <QRegularExpression>
#include <QMessageBox>
#include "protocol.h"
ParkingSpotPage::ParkingSpotPage(QWidget *parent, QTcpSocket *externalSocket) :
    QWidget(parent),
    ui(new Ui::ParkingSpotPage),
    socket(externalSocket)
{
    ui->setupUi(this);
    // 主垂直布局
    mainLayout = new QVBoxLayout(this);

    // 查询区域（水平布局）
    QHBoxLayout *queryLayout = new QHBoxLayout();
    QLabel *queryLabel = new QLabel("查询车位编号:");
    queryEdit = new QLineEdit("");
    queryEdit->setPlaceholderText("查询车位状态");
    QPushButton *queryButton = new QPushButton("查询");
    QPushButton *refreshButton = new QPushButton("刷新");

    queryLayout->addWidget(queryLabel);
    queryLayout->addWidget(queryEdit);
    queryLayout->addWidget(queryButton);
    queryLayout->addWidget(refreshButton);
    mainLayout->addLayout(queryLayout);

    // 添加颜色说明区域（水平布局）
    QHBoxLayout *legendLayout = new QHBoxLayout();

    // 绿色（可用）
    QLabel *greenLabel = new QLabel();
    greenLabel->setFixedSize(20, 20);
    greenLabel->setStyleSheet("background-color: green;");
    QLabel *greenText = new QLabel("可用");

    // 橙色（已预约）
    QLabel *orangeLabel = new QLabel();
    orangeLabel->setFixedSize(20, 20);
    orangeLabel->setStyleSheet("background-color: orange;");
    QLabel *orangeText = new QLabel("已被预约");

    // 红色（已占用）
    QLabel *redLabel = new QLabel();
    redLabel->setFixedSize(20, 20);
    redLabel->setStyleSheet("background-color: red;");
    QLabel *redText = new QLabel("已被占用");

    legendLayout->addWidget(greenLabel);
    legendLayout->addWidget(greenText);
    legendLayout->addSpacing(20); // 添加间距
    legendLayout->addWidget(orangeLabel);
    legendLayout->addWidget(orangeText);
    legendLayout->addSpacing(20); // 添加间距
    legendLayout->addWidget(redLabel);
    legendLayout->addWidget(redText);
    mainLayout->addLayout(legendLayout);


    // 查询按钮绑定槽函数
    connect(queryButton, &QPushButton::clicked, this,&ParkingSpotPage::handleSearch);
    //刷新按钮绑定槽函数
    connect(refreshButton,&QPushButton::clicked,this,&ParkingSpotPage::handleRefresh);
}

ParkingSpotPage::~ParkingSpotPage()
{
    delete ui;
}

void ParkingSpotPage::initUI(const QJsonObject &message)
{
    //qDebug() << message;
    QJsonArray vectorArray = message["vector"].toArray();

    QVector<int> statusVector;
    for (const QJsonValue &val : vectorArray) {
        statusVector.append(val.toInt());
    }
    for (int status : statusVector) {
        qDebug() << "Parking Spot Status:" << status;
    }

    // 车位网格区域（5行10列）
       int rows = 5;
       int cols = 10;
       int i =0;
       QGridLayout *gridLayout = new QGridLayout();
       for (int row = 0; row < rows; ++row) {
           for (int col = 0; col < cols; ++col) {
               QString spotId = QString("A-%1").arg(row * cols + col + 1);
               QPushButton *spot = new QPushButton(spotId);
               spotButtons.append(spot);
               spot->setFixedSize(60, 60);
               if(statusVector[i]==0)
                    spot->setStyleSheet("background-color: green;");
               else if(statusVector[i]==1)
                    spot->setStyleSheet("background-color: orange;");
               else if(statusVector[i]==2)
                   spot->setStyleSheet("background-color: red;");
               else
                   spot->setStyleSheet("background-color: gray;");
                i++;
               gridLayout->addWidget(spot, row, col);
           }
       }
       mainLayout->addLayout(gridLayout);
}

void ParkingSpotPage::refreshUI(const QJsonObject &message)
{
    QJsonArray vectorArray = message["vector"].toArray();

    QVector<int> statusVector;
    for (const QJsonValue &val : vectorArray) {
        statusVector.append(val.toInt());
    }
    for(int i = 0;i<50;i++)
    {
        if(statusVector[i]==0)
             spotButtons[i]->setStyleSheet("background-color: green;");
        else if(statusVector[i]==1)
             spotButtons[i]->setStyleSheet("background-color: orange;");
        else if(statusVector[i]==2)
            spotButtons[i]->setStyleSheet("background-color: red;");
        else
            spotButtons[i]->setStyleSheet("background-color: gray;");
    }

}

void ParkingSpotPage::handleServerMessage(const QJsonObject &message)
{
    QJsonObject message2 = message["message2"].toObject();
    int func2 = message["func2"].toInt();
    qDebug()<<"message2:"<<message2;
    qDebug()<<"func2:"<<func2;
    switch(func2)
    {
        case 1:
            initUI(message2);
            break;
        case 2:
            refreshUI(message2);
            break;
        case 3:
            showResearchResult(message2);
            break;
        default:
            qDebug()<<"ParkingSpotPage::handleServerMessage: other func2";
            break;
    }
}

void ParkingSpotPage::handleRefresh()
{
    QJsonObject root;
    QJsonObject message;
    root["func"] = 7;
    message["signal"] = 2;
    root["message"] = message;
    QByteArray dataToSend = Encode(root);
    socket->write(dataToSend);
}

void ParkingSpotPage::handleSearch()
{
    QJsonObject root;
    QJsonObject message;
    spot = queryEdit->text();
    if(!isValidFormat(spot))
    {
        QMessageBox *msg = new  QMessageBox(this);
        msg->setWindowTitle("警告");
        msg->setIcon(QMessageBox::Warning);
        msg->setText("请输入正确格式的车位");
        msg->show();
        queryEdit->setText("");
        return;
    }
    root["func"] = 8;
    message["spot"] = spot;
    root["message"] = message;
    QByteArray dataToSend = Encode(root);
    socket->write(dataToSend);
    queryEdit->setText("");
}


bool ParkingSpotPage::isValidFormat(const QString& str) {

    static QRegularExpression regex("^A-(\\d{1,2})$"); // 1到2位数字
    QRegularExpressionMatch match = regex.match(str);
    if (match.hasMatch()) {
        int number = match.captured(1).toInt();
        return number >= 1 && number <= 50;
    }
    return false;
}

void ParkingSpotPage::showResearchResult(const QJsonObject &message)
{
    QString status = message["status"].toString();
    QString plate = message["plate"].toString();
    if(status=="available")
    {
        QMessageBox *msg = new  QMessageBox(this);
        msg->setWindowTitle("查询结果");
        msg->setIcon(QMessageBox::Information);
        msg->setText(spot+"可用");
        msg->show();
    }
    else if(status=="reserved")
    {
        QMessageBox *msg = new  QMessageBox(this);
        msg->setWindowTitle("查询结果");
        msg->setIcon(QMessageBox::Information);
        msg->setText(spot+"已被"+plate+"预约");
        msg->show();
    }
    else
    {
        QMessageBox *msg = new  QMessageBox(this);
        msg->setWindowTitle("查询结果");
        msg->setIcon(QMessageBox::Information);
        msg->setText(spot+"已被"+plate+"占用");
        msg->show();
    }


}


